package com.foreveross.pushsdk.main;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import com.foreveross.pushsdk.core.IMessageReceiver;
import com.foreveross.pushsdk.entity.Tags;

/**
 * 继承自这个类的Service必须在重载onCreate，并在super.onCreate()之前对userId
 * ,serverHost,serverPort,messageReceiver,tages进行初始化。
 * 为了保证稳定性，请用全局异常捕获，并在发生全局异常后关闭Service。
 * 需要的权限:
 * android.permission.ACCESS_NETWORK_STATE
 * android.permission.INTERNET
 * android.permission.ACCESS_WIFI_STATE 
 * @author Huang Li
 * @version 创建时间：2014年5月12日
 */
public class PushService extends Service {
    private PushManager manager;
    private ConnectivityReceiver receiver;
    protected String userId,serverHost;
    protected int serverPort;
    protected String appId;
    protected String secret;
    /**
     * 消息的接收器
     */
    protected IMessageReceiver messageReceiver;
    protected Tags[] tagses;
    @Override
    public  void onCreate()  {
        Log.i(PushConfig.LOG_TAG,"Push Service is create");
        if(manager==null){
            manager=PushManager.getInstance();
            if(userId==null||userId.equals("")||
                    serverHost==null||serverHost.equals("")||
                    serverPort==0){
                try {
                    throw new Exception("Please initialize userId,serverHost,serverPort first");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return;
                }
            }
            manager.init(getApplicationContext(), userId, serverHost, serverPort,messageReceiver,tagses,secret,appId);
        }
        receiver=new ConnectivityReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);

        super.onCreate();
    }
    //如果以startService 启动就调用这个
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Log.i(PushConfig.LOG_TAG, "Push Service is onStartCommand");
        connectToServer();
        return super.onStartCommand(intent, flags, startId);
    }
    //如果以bindService 启动就调用这个
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(PushConfig.LOG_TAG,"Push Service is onBind");
        connectToServer();
        return null;
    }

    public void connectToServer(){
        manager.connect();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Log.i(PushConfig.LOG_TAG,"Push Service is destroy");
        if(manager!=null)manager.close();
        manager=null;
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            // TODO: handle exception
        }
        super.onDestroy();
    }
}
